# -*- coding:utf-8 -*-
from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer
from channels.exceptions import StopConsumer, AcceptConnection, DenyConnection, InvalidChannelLayerError
from asgiref.sync import async_to_sync
import json

from django.core.cache import cache
import logging

logger = logging.getLogger("django")


class ChatConsumer(WebsocketConsumer):
    """
    发送同步菜单，同步退出登陆
    """

    # groups 记录当前登陆的用户
    # groups = ["admin1", "admin2"]

    def websocket_connect(self, message):
        group = self.scope["url_route"]["kwargs"].get("pk")

        async_to_sync(self.channel_layer.group_add)(group, self.channel_name)

        try:
            self.connect()
        except AcceptConnection:
            self.accept()
        except DenyConnection:
            self.close()

    def websocket_disconnect(self, message):
        group = self.scope["url_route"]["kwargs"].get("pk")
        async_to_sync(self.channel_layer.group_discard)(group, self.channel_name)
        raise StopConsumer()

    def websocket_receive(self, text_data):
        """
        Called when a WebSocket frame is received. Decodes it and passes it
        to receive().
        """
        # if "text" in message:
        #     if message["text"] == "ping":
        #         self.send("pong")
        # else:
        #     logger.info(message["bytes"])
        # logger.info(text_data)
        # text = text_data["text"]
        # text_data_json = json.loads(text)
        # message = text_data_json["message"]
        group = self.scope["url_route"]["kwargs"].get("pk")
        async_to_sync(self.channel_layer.group_send)(group, {"type": "chat.message", "message": text_data})

    def chat_message(self, event):
        message = event["message"]
        # logger.info(message)
        self.send(text_data=json.dumps({"message": message}))
        """
        {"isLogin":true,"menu":""}
        """

################
# https://channels.readthedocs.io/en/latest/topics/channel_layers.html
# 在其他地方调用channel_layer
# 方法名chat_message ，在调用时 使用.代替，如:{"type": "chat.message"}

# from channels.layers import get_channel_layer
# from asgiref.sync import async_to_sync
#
# channel_layer = get_channel_layer()
#
#
# def send_msg(user_id, text):
#     async_to_sync(channel_layer.group_send)(user_id, {"type": "chat.message", "message": text})
#
# send_msg()
